package com.yy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yy.constant.AuthConstant;
import com.yy.domain.LoginSysUser;
import com.yy.mapper.LoginSysUserMapper;
import com.yy.model.SecurityUser;
import com.yy.strategy.LoginStrategy;
import com.yy.strategy.LoginStrategyFactory;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 描述
 * 作者 雷哥
 */
@Component
@Log4j2
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private LoginStrategyFactory loginStrategyFactory;

    /**
     * 和前端约定好。要求登录必须登录类型 并要求把类型loginType放到header
     * String SYS_USER_LOGIN = "sysUserLogin";  String MEMBER_LOGIN = "memberLogin";
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //得到用户登录的类型
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String loginType = request.getHeader(AuthConstant.LOGIN_TYPE);
        if (!StringUtils.hasText(loginType)) {
            //注意这个异常。要抛security能抓的异常
            throw new InternalAuthenticationServiceException("登录类型不能为空");
        }
        //根据登录类型去获取相应的登录策略
        LoginStrategy instance = loginStrategyFactory.getInstance(loginType);
        if (ObjectUtils.isEmpty(instance)) {
            throw new InternalAuthenticationServiceException("登录类型不支持");
        }
        return instance.realLogin(username);
    }
}
